import React from 'react'
import {
    View, ScrollView, RefreshControl
} from 'react-native'
import {
    List, ListItem, Header, SearchBar
} from 'react-native-elements'
import { getKeys, getItem } from '../utils/Storage'
import request, { getHeader, setHeader } from '../request'

export default class extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            list: [],
            refreshing: false,
            isLogin: false
        }
    }

    render() {
        return <View style={{ flex: 1 }}>
            <Header
                centerComponent={{ text: '密码库', style: { color: '#fff' }, onPress: () => this.login() }}
                rightComponent={{ icon: 'add', onPress: () => this.add(), color: '#fff' }}
            />
            <ScrollView style={{ flex: 1 }}
                refreshControl={<RefreshControl onRefresh={() => this.onRefresh()} refreshing={this.state.refreshing} />}>
                <List>
                    {this.state.list.map((item, index) => <ListItem
                        key={index}
                        switchButton
                        subtitle={item.additional}
                        title={item.title}
                        onPress={() => this.open(item.id)}
                    />)}
                </List>
            </ScrollView>
        </View>
    }
    async componentDidMount() {
        try {
            let token = await getItem("token");
            let res = await request.post('/login2', { token: token });
            setHeader("token", token);
            this.setState({ isLogin: true });
            let list = await request.post('/getlist');
            this.setState({ list })
        } catch (e) {
            this.setState({ isLogin: false });
            this.props.navigation.navigate("Login");
            return;
        }

        // this.list = await getKeys();
        // this.showData()
    }
    async onRefresh() {
        try {
            let list = await request.post('/getlist');
            this.setState({ list })
        } catch (e) {

        }
        // this.list = await getKeys();
        // this.showData()
    }
    // index = 0
    // async showData() {
    //     if (!this.list || this.index >= this.list.length) return;
    //     let data = await getItem(this.list[this.index])
    //     if (data) this.setState({ list: this.state.list.concat(data) });
    //     this.index++;
    //     this.showData();
    // }
    open(id) {
        this.props.navigation.navigate("Add", { id: id });
    }
    add() {
        this.props.navigation.navigate("Add");
    }
    login(){
        this.props.navigation.navigate("Login");
    }
}